<template>
  <div>
    <div class="desc">
      <div class="title">1.用途：</div>
      <div class="content">
        对原生js的sessionStorage进行的封装，实现了响应式的Session本地存储
      </div>
      <el-button @click="setSessionStorage" class="el-btn">设置sessionStorage</el-button>
      <div class="title">2.合并默认值</div>
      <div class="title">2.1合并浅合并</div>
      <div class="content">设置mergeDefaults:true是浅合并</div>
      <el-button @click="mergeSessionStorage" class="el-btn">合并sessionStorage</el-button>
      <div class="title">3.自动序列化</div>
      <div class="content">
        useSessionStorage将根据提供的序列化方法。比如JSON.stringify/JSON.parse将用于对象，Number.toString/parseFloat将用于数字等。
      </div>
      <el-button @click="serializerSessionStorage"
      class="el-btn">序列化sessionStorage</el-button
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import { StorageSerializers, useSessionStorage } from "@vueuse/core";
const setSessionStorage = () => {
  // 响应式对象
  const state = useSessionStorage("key-store", {
    id: 100,
    url: "https://www.liu.com",
  });
  // 绑定 boolean
  const flag = useSessionStorage("key-flag", true); // returns Ref<boolean>

  // 绑定数字
  const count = useSessionStorage("key-count", 0); // returns Ref<number>
  // 设置定时器修改对象
  setInterval(() => {
    state.value.id = 200;
    flag.value = false;
    // 删除本地存储
    state.value = null;
    flag.value = null;
  }, 5000);
};
const mergeSessionStorage = () => {
  localStorage.setItem("key_user", '{"id":222}');
  //用useSessionStorage绑定对象
  const userInfo = useSessionStorage(
    "key_user",
    { id: 1, url: "https://www.liu.com" },
    { mergeDefaults: true }
  );
};
const serializerSessionStorage = () => {
  const item = useSessionStorage(
    "key",
    { id: "liu" },
    {
      serializer: {
        read: (v: any) => (v ? JSON.parse(v) : null),
        write: (v: any) => JSON.stringify(v),
      },
    }
  );
};
</script>

<style scoped>
.title {
  font-size: 18px;
  line-height: 60px;
  font-weight: bolder;
}
.content {
  margin-bottom: 20px;
  padding-left: 40px;
}
.el-btn {
    margin-left: 40px;
}
</style>